package cn.mcartoon.interceptor;

import cn.mcartoon.constants.Constants;
import cn.mcartoon.dto.ResultEnum;
import cn.mcartoon.utils.ResponseOutput;
import cn.mcartoon.utils.redis.RedisKeyUtil;
import cn.mcartoon.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前端拦截器
 */

@Component
public class BaseInterceptor extends HandlerInterceptorAdapter {

    Logger log = LoggerFactory.getLogger(BaseInterceptor.class);


    /**
     * 直接放行的接口
     */
    public static String[] EXCLUDE_URI = new String[]{"/pay/wxPay/notify", "/users/wechat/callback", "/users/login/wechat"};

    /**
     * 需要登录才可以访问的接口
     */
    public static String[] VERIFY_URI = new String[]{"/api/chapter/buy", "/api/recharge/submit", "/api/pay/codeUrl/"
            ,"/api/chapter/content/list","/api/chapter/list","/api/cartoon/detail"};

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        boolean flag = false;
        String loginUser = null;
        String key = null;

        // 获取请求路径
        String url = request.getServletPath();
        // 直接放行接口
        for(String s: EXCLUDE_URI){
            if(url.contains(s)){
                return true;
            }
        }
        // 公共入参校验
        String timestamp = request.getHeader("timestamp");
        String sourceType = request.getHeader("source-type");
        if(StringUtils.isBlank(timestamp)){
            log.info("公共入参【timestamp】不能为空 ");
            ResponseOutput.outputJson(response, ResultEnum.FAIL_TIMESTAMP_NOT_NULL);
            return false;
        }
        if(StringUtils.isBlank(sourceType)){
            log.info("公共入参【sourceType】不能为空 ");
            ResponseOutput.outputJson(response, ResultEnum.FAIL_VISIT_SOURCE_NOT_NULL);
            return false;
        }

        for (String s : VERIFY_URI) {
            if (url.contains(s)) {
                flag = true;
                break;
            }
        }
        // 判断，如果是需要拦截的方法
        if (flag) {
            String token = request.getHeader("token");
            key = RedisKeyUtil.formatKeyWithPrefix(Constants.Redis.PREFIX_TOKEN + token);
            // 获取登录用户
            loginUser = redisUtils.getValue(key);
            log.info("Basenterceptor-->获取到用户登录信息users:{}", loginUser);
            // 验证用户登陆
            if (null == loginUser) {
                ResponseOutput.outputJson(response, ResultEnum.FILE_NOT_LOGIN);
                return false;
            }
        }
        // 如果用户是登录状态，登录状态续命
        if(!StringUtils.isBlank(key) && !StringUtils.isBlank(loginUser)){
            redisUtils.putValue(key, loginUser, Constants.Duration.HALF_AN_HOUR);
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub
    }

}